package com.qianchang.microfinance.view.mine.bill;

import android.graphics.Paint;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;

import com.bigkoo.pickerview.model.IPickerViewData;
import com.dm.library.http.DMOKHttpUtils;
import com.dm.library.http.HttpParams;
import com.dm.library.http.base.JsonResult;
import com.dm.library.http.callback.RequestCallBack;
import com.dm.library.utils.StringUtils;
import com.dm.library.utils.ToastUtil;
import com.dm.library.widgets.element.DTextView;
import com.qianchang.microfinance.R;
import com.qianchang.microfinance.bean.LoanUsageBean;
import com.qianchang.microfinance.bean.RechargeFixBean;
import com.qianchang.microfinance.bean.RechargeListItemBean;
import com.qianchang.microfinance.bean.RenewLoanBean;
import com.qianchang.microfinance.bean.SettleLoanBean;
import com.qianchang.microfinance.bean.SubmitLoanBean;
import com.qianchang.microfinance.bean.event.AgreementTitleBean;
import com.qianchang.microfinance.global.ConstantAppInfo;
import com.qianchang.microfinance.global.DMApplication;
import com.qianchang.microfinance.utils.DMConstant;
import com.qianchang.microfinance.utils.SpanUtils;
import com.qianchang.microfinance.view.base.BaseActivity;
import com.qianchang.microfinance.view.credit.data.ConfirmInfoJinbaoActivity;
import com.qianchang.microfinance.view.dialog.CommonDialog;
import com.qianchang.microfinance.view.mine.RechargeFixActivity;
import com.qianchang.microfinance.view.mine.loan.RepayPlanActivity;
import com.qianchang.microfinance.view.register.AgreementActivity;
import com.qianchang.microfinance.view.register.AgreementApi;

import org.json.JSONArray;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class RenewloanActivity extends BaseActivity implements View.OnClickListener, CommonDialog.OnItemSelectListener{
    @BindView(R.id.tv_settle_money) //结清金额
    DTextView tv_settle_money;

    @BindView(R.id.renew_apply_amount)  //续贷金额
    DTextView renew_apply_amount;

    @BindView(R.id.renew_deadline)  //续贷期限
    DTextView renew_deadline;

    @BindView(R.id.renew_serviceFeeRate) // 利率
    DTextView tv_serviceFeeRate;

    @BindView(R.id.renew_repaymentType)  //还款方式
    DTextView renew_repaymentType;

    @BindView(R.id.renew_plan)  //还款计划
    TextView renew_plan;

    @BindView(R.id.tv_pri)
    DTextView tv_pri;   //待还本金

    @BindView(R.id.tv_rate)
    DTextView tv_rate;

    @BindView(R.id.renew_money)
    DTextView renew_money;  //先行放款

    @BindView(R.id.renew_bri)
    DTextView renew_bri; //过桥费

    @BindView(R.id.renew_service)
    DTextView renew_service; //贷款服务费
    @BindView(R.id.tv_re_loan)
    DTextView tv_re_loan;

    @BindView(R.id.tv_protocol)
    DTextView tv_protocol; //协议

    @BindView(R.id.ck_protocol)
    CheckBox ckProtocol;

    @BindView(R.id.btn_renewloan) //确定申请续贷
    Button btn_renewloan;
    private String projectId;
    private RenewLoanBean renewLoanBean;
    private double re_rate;
    private static final int LOAN_USAGE = 2;
    private int loanUsageInt = -1;
    private String loan_deline;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_renewloan);
        ButterKnife.bind(this);
        initView();
        initData();
    }

    @Override
    protected void initView() {
        super.initView();
        setTitleName(getString(R.string.Label_Renewal));
        renew_plan.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG ); //下划线
        renew_plan.getPaint().setAntiAlias(true);//抗锯齿

        renew_deadline.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG ); //下划线
        renew_deadline.getPaint().setAntiAlias(true);//抗锯齿


        btn_renewloan.setOnClickListener(this);
        renew_plan.setOnClickListener(this);
        renew_deadline.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        super.initData();
        Bundle bundle = getBundle();
        if (null != bundle) {
            projectId = bundle.getString(ConstantAppInfo.PROJECT_ID);
        }
        getRenewData();
        AgreementData();
    }

    /**
     * 获取续贷金额
     */
    private void getRenewData() {
      show();
    String userId = DMApplication.getInstance().getmUserLoginInfo().getUserId();
        HttpParams params = new HttpParams();
        params.put("projectId", projectId);
        params.put("userId", userId);
        if(StringUtils.isEmpty(loan_deline)){

        }else {
            params.put("period", loan_deline);
        }
        DMOKHttpUtils.getInstance().post(this, DMConstant.ApiURL.RENEW_LOAN, params, new RequestCallBack<RenewLoanBean>() {
            @Override
            public void onSuccess(JsonResult<RenewLoanBean> response) {
                dismiss();
                if (response.isReqDataSuccess()) {
                    renewLoanBean = response.getObject();
                    if (null != renewLoanBean) {
                     refreshUi(renewLoanBean);
                    }
                } else {
                    ToastUtil.getInstant().show(RenewloanActivity.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(RenewloanActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {

            }
        });
    }

    private void refreshUi(RenewLoanBean renewLoanBean) {

        if(renewLoanBean!=null){
            tv_settle_money.setTextContent(renewLoanBean.getSettleMoney());
            renew_apply_amount.setTextContent(renewLoanBean.getContinuedLoadMoney());
           // renew_deadline.setTextContent(renewLoanBean.getPeriod()+"个月");
            double a = Double.parseDouble(renewLoanBean.getRate());
             re_rate=a/100;
//            tv_serviceFeeRate.setTextContent(re_rate+"%/月");
            tv_serviceFeeRate.setTextContent(renewLoanBean.getRate()+"%/月");
            renew_repaymentType.setTextContent(renewLoanBean.getRepeymentTypeStr());
            tv_pri.setTextContent(renewLoanBean.getTotalPrincipal());
            tv_rate.setTextContent(renewLoanBean.getTotalInterest());
            tv_re_loan.setTextContent(renewLoanBean.getTotalOverdue());
            renew_money.setTextContent(renewLoanBean.getMoney());
            renew_bri.setTextContent(renewLoanBean.getGqf()+"%");
            renew_service.setTextContent(renewLoanBean.getServiceFee()+"%");
        }

    }
    /**
     * 获取续贷金额
     */
    private void goRenewData() {
        show();
        String userId = DMApplication.getInstance().getmUserLoginInfo().getUserId();
        HttpParams params = new HttpParams();
        params.put("oldProjectId", projectId);
        params.put("applyAmount", renewLoanBean.getContinuedLoadMoney());
        params.put("period", loan_deline);
        DMOKHttpUtils.getInstance().post(this, DMConstant.ApiURL.GO_RENEW_LOAN, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(JsonResult<String> response) {
                dismiss();
                if (response.isReqDataSuccess()) {
                    ToastUtil.getInstant().show(RenewloanActivity.this, response.getDescription());
                    startActivity(RenewSucceedActivity.class,true);
                } else {
                    ToastUtil.getInstant().show(RenewloanActivity.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(RenewloanActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {

            }
        });
    }

    @Override
    public void onClick(View view) {
        CommonDialog.Builder builder = new CommonDialog.Builder();
        builder.setContext(this).setOnItemSelectListener(RenewloanActivity.this);
        switch ( view.getId()){
            case  R.id.btn_renewloan:
                if(StringUtils.isEmpty(loan_deline)){
                    ToastUtil.getInstant().show(this, "请选择续贷期限");
                    return;
                }
                if (!ckProtocol.isChecked()) {
                    ToastUtil.getInstant().show(RenewloanActivity.this, getString(R.string.msg_read_loan_agreement));
                    return;
                }
                goRenewData();
                break;
            case R.id.renew_plan:
                if(StringUtils.isEmpty(loan_deline)){
                    ToastUtil.getInstant().show(this, "请选择续贷期限");
                    return;
                }
                Bundle bundle = new Bundle();
                bundle.putString("applyAmount", renewLoanBean.getContinuedLoadMoney()); //借款金额
                bundle.putString("repaymentType", renewLoanBean.getRepeymentType());// //还款方式
                bundle.putString("deadline",loan_deline);    //借款期限
                bundle.putDouble("reta", re_rate); //利率（月）
                startActivity(LoanPlanActivity.class, bundle);
                break;
            case  R.id.renew_deadline:

                builder.setData(getLoanUsageData()).setFlag(LOAN_USAGE).setTitle("续贷期限");


                break;
        }
        builder.build().showPickerView();
    }

    @Override
    public void onItemSelect(IPickerViewData iPickerViewData, int position, int flag) {
        LoanUsageBean loanUsageBean = (LoanUsageBean)iPickerViewData;
        if(loanUsageBean != null){
            renew_deadline.setTextContent(loanUsageBean.getName()+"个月");
            loanUsageInt = loanUsageBean.getValue();
            loan_deline = loanUsageBean.getName();
            getRenewData();
        }else {
            renew_deadline.setTextContent("");
            loanUsageInt = -1;
        }
    }
    public List<LoanUsageBean> getLoanUsageData(){
        List<LoanUsageBean> list = new ArrayList<>();

        LoanUsageBean loanUsageBean = new LoanUsageBean();
        loanUsageBean.setName("6");
        loanUsageBean.setValue(0);

        LoanUsageBean educationBean = new LoanUsageBean();
        educationBean.setName("12");
        educationBean.setValue(1);


        list.add(loanUsageBean);
        list.add(educationBean);
        return list;
    }
    private void AgreementData(){

        JSONArray js = new JSONArray();
        js.put("12");

        AgreementApi.getAgreementName(this, js, new AgreementApi.AgreementNameCallBack() {
            @Override
            public void success(List<AgreementTitleBean> agreementName) {
                if (null != agreementName && !agreementName.isEmpty()) {

                    tv_protocol.setMovementMethod(LinkMovementMethod.getInstance());
                    tv_protocol.setHighlightColor(getResources().getColor(android.R.color.transparent));
                    SpanUtils spanUtils = new SpanUtils();
                    spanUtils.append("我同意接受").setForegroundColor(getResources().getColor(R.color.common_black_color_6)).append("《" + agreementName.get(0).getAgreementName() + "》").setClickSpan(new ClickableSpan() {
                        @Override
                        public void onClick(View view) {
                            Bundle bundle = new Bundle();
                            bundle.putSerializable(ConstantAppInfo.AGREEMENT_ID, "12");
                            startActivity(AgreementActivity.class, bundle);
                        }

                        @Override
                        public void updateDrawState(TextPaint ds) {
                            ds.setColor(getResources().getColor(R.color.common_blue_color_light));
                            ds.setUnderlineText(false);
                        }
                    });

                    tv_protocol.setText(spanUtils.create());
                }
            }
        });
    }
}
